package com.ced.sip.common.biz.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.ced.base.biz.impl.BaseBizImpl;
import com.ced.base.entity.BaseAttachment;
import com.ced.base.exception.BaseException;
import com.ced.base.utils.GlobalSettingBase;
import com.ced.sip.common.biz.IAttachmentBiz;
import com.ced.sip.common.entity.Attachment;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.FtpUtil;
import com.ced.sip.common.utils.StringUtil;
public class AttachmentManagerImpl extends BaseBizImpl implements IAttachmentBiz  {
	/**
	 * 根据主键获得附件表实例
	 * @param id 主键
	 * @return
	 * @throws BaseException 
	 */
	public Attachment getAttachment(Long id) throws BaseException {
		return (Attachment)this.getObject(Attachment.class, id);
	}	
	/**
	 * 添加附件信息
	 * @param Attachment 附件表实例
	 * @throws BaseException 
	 */
	public void saveAttachment(Attachment Attachment) throws BaseException{
		this.saveObject( Attachment ) ;
	}
	
	/**
	 * 更新附件表实例
	 * @param Attachment 附件表实例
	 * @throws BaseException 
	 */
	public void updateAttachment(Attachment Attachment) throws BaseException{
		this.updateObject( Attachment ) ;
	}
	
	/**
	 * 删除附件表实例
	 * @param id 主键数组
	 * @throws BaseException 
	 */
	public void deleteAttachment(String id) throws BaseException {
		this.removeObject( this.getAttachment( new Long(id) ) ) ;
	}
	
	/**
	 * 删除附件表实例
	 * @param Attachment 附件表实例
	 * @throws BaseException 
	 */
	public void deleteAttachment(Attachment Attachment) throws BaseException {
		this.removeObject( Attachment ) ;
	}
	
	/**
	 * 删除附件表实例
	 * @param id 主键数组
	 * @throws BaseException 
	 */
	public void deleteAttachments(String[] id) throws BaseException {
		if( id != null )
			this.removeBatchObject(Attachment.class, id) ;
	}
	
	
	/**
	 * 获得所有附件表数据集
	 * @param attachment 查询参数对象
	 * @return
	 * @throws BaseException 
	 */
	public List getAttachmentList(  Attachment attachment ) throws BaseException {
		StringBuffer hql = new StringBuffer(" from Attachment att where 1 = 1 " );

		if ( !StringUtil.isBlank( attachment.getAttachmentType() )) {
			hql.append( " and att.attachmentType='" ).append( attachment.getAttachmentType() ).append( "'" ) ;
		}

		hql.append( " and att.attachmentField='" ).append( attachment.getAttachmentField() ).append( "'" ) ;
		

		hql.append(" and att.attachmentTypeId= ").append( attachment.getAttachmentTypeId() ) ;
		
		if ( !StringUtil.isBlank( attachment.getWriter() )) {
			hql.append(" and att.writer= '").append( attachment.getWriter() ).append("'") ;
		}
		
		hql.append(" order by att.attachmentId asc ");
		//System.out.println(hql);
		return baseDao.getObjects( hql.toString() );
	}

	/**
	 * 获得所有附件表数据集
	 * @param attachment 查询参数对象
	 * @return
	 * @throws BaseException 
	 */
	public Map<String,Object> getAttachmentMap(Attachment attachment ) throws BaseException {
		Map<String,Object> map = new HashMap<String,Object>();
		// 上传附件生成的uuid
		String uuIdData="";
		// 附件名
		String fileNameData="";
		// 附件格式
		String fileTypeData="";
		String  attIdData="";
		List list = getAttachmentList(attachment);
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				attachment=(Attachment)list.get(i);
				//二期上线以前的附件要取attachmentId作uuid
				if(attachment.getUuid()==null)attachment.setUuid(attachment.getAttachmentId()+"");
				if(i==(list.size()-1)){
					uuIdData+="\""+attachment.getUuid()+"\"";
					fileNameData+="\""+attachment.getAttachmenetName()+"\"";
					fileTypeData+="\""+attachment.getFileType()+"\"";
					attIdData+="\""+attachment.getAttachmentId()+"\"";
				}else{
					uuIdData+="\""+attachment.getUuid()+"\",";
					fileNameData+="\""+attachment.getAttachmenetName()+"\",";
					fileTypeData+="\""+attachment.getFileType()+"\",";
					attIdData+="\""+attachment.getAttachmentId()+"\",";
				}
			}
		}
		map.put("uuIdData", "["+uuIdData+"]");
		map.put("fileNameData", "["+fileNameData+"]");
		map.put("fileTypeData", "["+fileTypeData+"]");
		map.put("attIdData", "["+attIdData+"]");
		return map;
	}
	
	/**
	 * 
	 * @param formFile
	 * @param parentId
	 * @param clazz
	 * @param filed当附件为多种类型时，使用.对象的属性名称
	 * @throws BaseException
	 */
	public void saveAttachment(File formFile, Long parentId, Class clazz, String filed)
		throws BaseException {
		String tableName = StringUtil.getClassName(clazz);
		try {
			if ( ! StringUtil.isBlank( formFile )) {

			Attachment attachment = new Attachment();
			this.saveAttachment( attachment );

//			attachment.setAttachmenetName(formFile.getFileName());
			//temp
			attachment.setAttachmenetName(filed );
			attachment.setAttachmentType(tableName);
			attachment.setAttachmentTypeId(parentId);
			attachment.setWriteDate(new Date());

			if (!StringUtil.isBlank(filed)) {
				attachment.setAttachmentField("01");
			}

			// 真实环境nas服务器。通过ftp协议上传
			FtpUtil ftpUtil = new FtpUtil();
			ftpUtil.uploadFile(getAttachmentPath(attachment), new FileInputStream(formFile),FtpUtil.getOperatorFileName(attachment));
			
//			String fileName = ftpUtil.upload(getAttachmentPath(attachment), formFile
//					.getInputStream(), FtpUtil.getOperatorFileNameNoExtendName(attachment), true);

			this.updateAttachment( attachment );
			}
		} catch (Exception e) {
			throw new BaseException("上传附件错误：" + tableName, e);
		}

	} 

	/**
	 * 获取附件的上传路径-相对 
	 * @param attachment
	 * @return
	 */
	public String getAttachmentPath(Attachment attachment) {

		StringBuffer path = new StringBuffer( GlobalSettingBase.getAttachmentUploadLoaction() ) ;

		String year  = DateUtil.getYear(attachment.getWriteDate());
		String month = DateUtil.getMonth(attachment.getWriteDate());

		// 附件存放在以时间命名的文件夹中,
		path.append( File.separator ) ;
		path.append( attachment.getAttachmentType() ) ;
		path.append( File.separator ) ;
		path.append( year ) ;
		path.append( File.separator ) ;
		path.append( month ) ;
		path.append( File.separator ) ;
		
		return path.toString() ;
	}
	/**
	 * 获取ftp附件下载的url
	 * @param attachmentId
	 * @return
	 */
	public String getFtpAttachmentUrl(Attachment attachment, HttpServletRequest request) {

		StringBuffer url = new StringBuffer( request.getContextPath() ) ;
		
		url.append( "/download_down.action" ) ;
		url.append( "?attach.attachmentId=" ) ;
		url.append( attachment.getAttachmentId() ) ;
		
		if( attachment.getAttachmentField() != null ) {
			url.append( "&attach.attachmentField=" + attachment.getAttachmentField() ) ;
		}
		
		return url.toString() ;
	}

	/**
	 * 获取ftp附件完整显示url
	 * @param attachment 
	 * @return
	 */
	public String getFtpAttachmentViewUrl(Attachment attachment ) {

		StringBuffer url = new StringBuffer( "FTP://" ) ;
		url.append( GlobalSettingBase.getFileServerFtpUser() ).append( ":" ) ;
		url.append( GlobalSettingBase.getFileServerFtpPassword() ).append( "@" ) ;
		url.append( GlobalSettingBase.getAttachdmentPlacedFtpAddress() ).append( ":" ) ;
		url.append( GlobalSettingBase.getAttachdmentPlacedFtpAddressPort() ) ;
		url.append( this.getAttachmentRealPath( attachment, "")) ;
		url.append( FtpUtil.getOperatorFileName(attachment) ) ;
		
		return url.toString() ;
	}
	
	/**
	 * 获取附件的真实路径 上传到本机需要知道真实路径
	 * @param attachment 附件对象实例 
	 * @param abspath 相对开始路径, 从配置文件中取
	 * @author ted 2011-05-28 
	 * @return String 完整的真实路径
	 */
	public String getAttachmentRealPath(Attachment attachment, String abspath) {

		//GlobalSetting.getAttachmentRealUploadLocation()
		StringBuffer path = new StringBuffer( ""  ) ;
		
		if( abspath != null && abspath.length()>0 ) {
			path.append( abspath ) ;
			
		}else { // 默认值
			path.append( GlobalSettingBase.getAttachmentUploadLoaction() ) ;
		}
		
		// 年份
		String year = DateUtil.getYear(attachment.getWriteDate());
		
		// 月份
		String month = DateUtil.getMonth(attachment.getWriteDate());

		// 附件存放在以时间命名的文件夹中
		path.append( File.separator ) ;
		path.append( attachment.getAttachmentType() ) ;
		path.append( File.separator ) ;
		path.append( year ) ;
		path.append( File.separator ) ;
		path.append( month ) ;
		path.append( File.separator ) ;
		
		return path.toString() ;
	}
	
	/**
	 * 获取附件的url
	 * 
	 * @param attachmentId
	 * @return
	 */
	public String getAttachmentUrl(Attachment attachment, HttpServletRequest request) {

		StringBuffer url = new StringBuffer( request.getContextPath() ) ;
		//download_down.action?attach.attachmentId=11&attach.attachmentField=01
		
		// 调整附件下载方式 Ted 2011-08-25 
		url.append( "/download_down.action?" ) ;
		url.append( "attach.attachmentId=" ) ;
		url.append( attachment.getAttachmentId().longValue() ) ;
		
		// 增加附件代码类型 Ted 2011-06-02 
		if( attachment.getAttachmentField() != null ) {
			url.append( "&execPath=" + attachment.getAttachmentField() ) ;
		}
		
		return url.toString() ;
	}
	
	/**
	 * 获取页面附件的URL地址
	 * @param attachments 附件
	 * @param viewType 显示类型 0 查看 1 修改
	 * @param request 
	 * @author ted Ted 2011-01-05 
	 * @return
	 */
	public String getAttachmentPageUrl( List attachments, String viewType, HttpServletRequest request ) {
		String attachmentName = "" ;
		
		if( attachments !=null && attachments.size()>0 ){
			for(int i=0; i<attachments.size(); i++){
				Attachment attachment = (Attachment)attachments.get(i);
				Long attachmentId 		= attachment.getAttachmentId(); 
				
				if( "0".equals( viewType ) ) { // 查看
					if(i>0 ){
						attachmentName+="<br>";
					}
					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\"><img src='"+request.getContextPath()+this.getAttachImg(attachment.getFileType())+"'>  "+attachment.getAttachmenetName()+"</a>" ;
				}else if( "1".equals( viewType ) ){  //已上传  
					if(i>0 ){
						attachmentName+="<br>";
					}
//					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_parent\">"+attachment.getAttachmenetName()+"</a>" ;
				}else if( "2".equals( viewType ) ){  //供方管理授权书 
 					if(i>0 ){
						attachmentName+="<br>";
					}
					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\">"+"授权书"+"</a>" ;
				}else if( "3".equals( viewType ) ){	//标准管理列表页附件名显示为“附件”
					if(i>0 ){
						attachmentName+="<br>";
					}
					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\">"+"附件"+"</a>" ;
				}else { // 修改
					attachmentName	+= " <div id=\"" + attachmentId + "\"> <a href=\"" + this.getAttachmentUrl(attachment,request) + "\">" + attachment.getAttachmenetName() + "</a>&nbsp;" ;
					attachmentName	+= " <a href='#' onClick=\"removeAttachment('" + attachmentId + "');return false;\">" + " <font color=#ff0000>删除</font></a> </div> " ;
				}
			}
		}
		
		return attachmentName ;
	
	}
	
	public String getAttachImg(String type)
	{
		String imgs="/images/filetype/";
		if("zip".equals(type) ||"rar".equals(type) )
		{
			imgs+="rar.png";
		}
		else if("docx".equals(type) || "doc".equals(type))
		{
			imgs+="doc.png";
		}
		else if("jpg".equals(type) || "jpeg".equals(type)|| "gif".equals(type)|| "png".equals(type)|| "bmp".equals(type)|| "tif".equals(type)|| "svg".equals(type))
		{
			imgs+="image.png";
		}
		else if("xls".equals(type) || "xlsx".equals(type))
		{
			imgs+="xls.png";
		}
		else if("pdf".equals(type))
		{
			imgs+="pdf.png";
		}else
		{
			imgs+="file.gif";
		}
		return imgs;
	}
	/**
	 * 获取页面附件的URL地址 (多个附件类型增加删除方法类型)
	 * @param attachments 附件
	 * @param viewType 显示类型 0 查看 1 修改
	 * @param methodType 删除方法(js) 
	 * @param request 
	 * @author ted Ted 2011-01-05 
	 * @return
	 */
	public String getAttachmentPageUrl( List attachments, String viewType, String methodType, HttpServletRequest request ) {
		String attachmentName = "" ;
		
		if( attachments !=null && attachments.size()>0 ){
			for(int i=0; i<attachments.size(); i++){
				Attachment attachment = (Attachment)attachments.get(i);
				Long attachmentId 		= attachment.getAttachmentId(); 
				
				if( "0".equals( viewType ) ) { // 查看
					if(i>0 ){
						attachmentName+="<br>";
					}
					attachmentName += "&nbsp;<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\">"+attachment.getAttachmenetName()+"</a>" ;
				
				}else { // 修改
					attachmentName	+= " <div id=\"" + attachmentId + "\"> <a href=\"" + this.getAttachmentUrl(attachment,request) + "\">" + attachment.getAttachmenetName() + "</a>&nbsp;" ;
					attachmentName	+= " <a href='#' onClick=\"" + methodType + "('" + attachmentId + "');\">" + " <font color=#ff0000>删除</font></a> </div> " ;
				}
			}
		}
		
		return attachmentName ;
	
	}

	/**
	 * 获取页面附件的URL地址（完整显示文件名）
	 * @param attachments 附件
	 * @param viewType 显示类型 0 查看 1 修改
	 * @param request 
	 * @author ted Ted 2011-01-05 
	 * @return
	 */
	public String getAttachmentPageAllUrl( List attachments, String viewType, HttpServletRequest request ) {
		String attachmentName = "" ;
		
		if( attachments !=null && attachments.size()>0 ){
			for(int i=0; i<attachments.size(); i++){
				Attachment attachment = (Attachment)attachments.get(i);
				Long attachmentId 		= attachment.getAttachmentId(); 
				
				if( "0".equals( viewType ) ) { // 查看
					if(i>0 ){
						attachmentName+="<br>";
					}
					if(attachment.getAttachmenetName().length()>8){
						 attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\" title=\""+attachment.getAttachmenetName()+"\" >"+attachment.getAttachmenetName()+"</a>" ;
					}
					else
						attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\">"+attachment.getAttachmenetName()+"</a>" ;
				}else if( "1".equals( viewType ) ){  //已上传  
					if(i>0 ){
						attachmentName+="<br>";
					}
//					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_parent\">"+"已上传"+"</a>" ;
					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_parent\">"+attachment.getAttachmenetName()+"</a>" ;
				}else if( "2".equals( viewType ) ){  //供方管理授权书 
 					if(i>0 ){
						attachmentName+="<br>";
					}
					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\">"+"授权书"+"</a>" ;
				}else if( "3".equals( viewType ) ){	//标准管理列表页附件名显示为“附件”
					if(i>0 ){
						attachmentName+="<br>";
					}
					attachmentName += "<a href=\""+this.getAttachmentUrl(attachment,request)+"\" target=\"_blank\">"+"附件"+"</a>" ;
				}else { // 修改
					attachmentName	+= " <div id=\"" + attachmentId + "\"> <a href=\"" + this.getAttachmentUrl(attachment,request) + "\">" + attachment.getAttachmenetName() + "</a>&nbsp;" ;
					attachmentName	+= " <a href='#' onClick=\"removeAttachment('" + attachmentId + "');return false;\">" + " <font color=#ff0000>删除</font></a> </div> " ;
				}
			}
		}
		
		return attachmentName ;
	
	}
	
	/**
	 * 附件上传   多文件上传
	 * @param att 附件对象实例 
	 * @author lgl
	 * @return String 完整的真实路径
	 */
	public void saveAttachmentAndUpload( BaseAttachment att ) throws FileNotFoundException, Exception {
		if ( att != null ) {			
			if( att.getUuIdData() != null ) {
			    String[] attIds=att.getAttIdData().split(",");
			    String[] uuids=att.getUuIdData().split(",");
			    String[] fileNames=att.getFileNameData().split(",");
			    String[] fileTypes=att.getFileTypeData().split(",");
				for(int i=0; i<uuids.length; i++ ){	
					if(attIds[i].equals("0")){
					Attachment attachment= new Attachment() ;					
					attachment.setAttachmenetName( fileNames[i] ) ;
					attachment.setAttachmentField( att.getAttachmentField() ) ;
					attachment.setAttachmentType( att.getAttachmentType() ) ;
					attachment.setAttachmentTypeId( att.getAttachmentTypeId() ) ;
					attachment.setWriteDate( att.getWriteDate() ) ;
					attachment.setWriter( att.getWriter() ) ;
					//如果是二期上线之前的附件，没有uuid，所以更新的时候也不存在uuid
					if(uuids[i].length()==36) attachment.setUuid(uuids[i]);
					attachment.setFileType(fileTypes[i]);	
					
					this.saveAttachment( attachment );		
					}
				}
			}
		}
	}
	/**
	 * 附件上传 单文件上传
	 * @param att 附件对象实例 
	 * @author lgl
	 * @return String 完整的真实路径
	 */
	public void saveAttachmentAndUploadOne( BaseAttachment att ) throws FileNotFoundException, Exception {
		if ( att != null ) {

			File file=att.getUploadFiles()[0];
			if( file!= null ) {		
				    String uuId=UUID.randomUUID()+"";
				    String fileType="",fileName=att.getUploadFilesFileName()[0],operatorFileName="";
				    int index = fileName.lastIndexOf(".");
					if (index > -1) {
						fileType =fileName.substring(index);
					}
					fileType=fileType.toLowerCase().substring(1);
					operatorFileName=uuId +"."+ fileType;
					
					Attachment attachment= new Attachment() ;					
					attachment.setAttachmenetName( fileName) ;
					attachment.setAttachmentField( att.getAttachmentField() ) ;
					attachment.setAttachmentType( att.getAttachmentType() ) ;
					attachment.setAttachmentTypeId( att.getAttachmentTypeId() ) ;
					attachment.setWriteDate( att.getWriteDate() ) ;
					attachment.setWriter( att.getWriter() ) ;	
					attachment.setUuid(uuId);
					attachment.setFileType(fileType);
					this.saveAttachment( attachment );
			
					
					// 真实环境nas服务器。通过ftp协议上传
					FtpUtil ftpUtil = new FtpUtil();
					ftpUtil.uploadFile(getAttachmentPath(attachment), new FileInputStream(file), operatorFileName);
					this.updateAttachment( attachment );
				
			}
		}
	}

	/**
	 * 删除附件表实例
	 * @param att 附件对象实例 
	 * @author lgl 
	 * @return String 完整的真实路径
	 */
	public void deleteAttachments(String attachmentType, Long attachmentTypeId,
			String attachmentField) throws BaseException {
		String sql="delete from attachment where attachment_type='"+attachmentType+"' and attachment_type_id="+attachmentTypeId+" and attachment_field='"+attachmentField+"'";
		this.updateJdbcSql(sql);
		
	}
}
